<template>
  <div class="app-container customer-div">


    <div style="margin-top:40px">
      <el-form :inline="true" :model="listQuery1" size="mini" label-width="100px">
          <el-form-item label="月份：">
            <el-date-picker
              style="width:150px;margin-right: 10px"
              size="mini"
              value-format="yyyy-MM"
              placeholder="请选择月份"
              v-model="listQuery1.month"
              type="month"
              align="right">
            </el-date-picker>
          </el-form-item>
        <el-form-item label="品类：">
          <el-select size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px"  v-model="listQuery1.goodsClass" >
            <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厂家：" v-if="listQuery1.goodsClass">
          <el-input size="mini"  placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px"  v-model="listQuery1.brandName"></el-input>
        </el-form-item>
        <el-form-item label="采购员：">
          <el-select size="mini"
                     collapse-tags
                     v-model="listQuery1.userIds" clearable
                     placeholder="请选择人员" multiple>
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList1()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="listLoading1"
        :data="tableData1"
        :summary-method="getSummaries"
        show-summary
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
          label="采购员"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.userRealName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsNum"
          label="实际销量"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.goodsNum}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsNumTarget"
          label="目标销量"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span >{{scope.row.goodsNumTarget}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsNumDiff"
          label="销量差额"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span :style="{'color': scope.row.goodsNumDiff < 0 ? 'red' :'#606266'}">{{scope.row.goodsNumDiff}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsNumRate"
          label="销量完成率"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span :style="{'color':scope.row.goodsNumRate<100 ? 'red':'#606266'}">
              {{scope.row.goodsNumRate}}%
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="shipNum"
          label="实际出库量"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.shipNum}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="perShipProfit"
          label="实际吨毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span >{{scope.row.perShipProfit}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="perShipProfitTarget"
          label="目标吨毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span >{{scope.row.perShipProfitTarget}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="shipProfit"
          label="实际总毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.shipProfit}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="shipProfitTarget"
          label="目标总毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.shipProfitTarget}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="shipProfitDiff"
          label="总毛利差额"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span  :style="{'color':scope.row.shipProfitDiff<0 ? 'red':'#606266'}" >{{scope.row.shipProfitDiff}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="shipProfitRate"
          label="总毛利完成率"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span
              :style="{'color':scope.row.shipProfitRate < 100 ? 'red' : '#606266'}"
            >{{scope.row.shipProfitRate}}%</span>
          </template>
        </el-table-column>
      </el-table>
    </div>


  </div>
</template>
<script>
import {puserSaleNumAnalysis,goodsCategoryList} from '@/api/data.js'
import {getOrderUsersList} from '@/api/partner.js'
import store from '@/store'
import { mapGetters } from 'vuex'
import { formatDate } from '@/utils/date.js';

const defaultListQuery={
  "month" : "",
  "goodsClass" : "", //品类
  "brandName" : "",   //厂家
  userIds:[]
};



export default {
  name: "index",
  data(){
    return {
      roles:store.getters.roles ? store.getters.roles : [],
      props:{multiple: true,label:'value',value:'label',emitPath:false},
      listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData1: [],
      count1: 0,
      listLoading1: false,
      data:[],
      userList:[],
      classList:[]

    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  created() {
    this.getUserList()
    this.getClassList()
    this.listQuery1.month = this.getMonth('month')
    if(this.$route.query.dataMonth){
      this.listQuery1.month = this.$route.query.dataMonth
    }
    if(this.$route.query.dataGoodsClass){
      this.listQuery1.goodsClass = this.$route.query.dataGoodsClass
    }
    if(this.$route.query.dataBrandName){
      this.listQuery1.brandName = this.$route.query.dataBrandName
    }
    if(this.$route.query.dataUserIds){
      let userIds = this.$route.query.dataUserIds.split(",")
      this.listQuery1.userIds = userIds.map(item => Number(item));
    }
    this.getList1();
  },
  filters: {

  },
  methods:{
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if(column.property == 'goodsNumRate'){
          sums[index] = this.sumRatefn('goodsNum','goodsNumTarget',0) + '%'
        }else if(column.property == 'shipProfitRate'){
          sums[index] = this.sumRatefn('shipProfit','shipProfitTarget',0)+ '%'
        }else if(column.property == 'goodsNumDiff'){
          sums[index] = this.sumDifffn('goodsNum','goodsNumTarget',3)
        }else if(column.property == 'shipProfitDiff'){
          sums[index] = this.sumDifffn('shipProfit','shipProfitTarget',3)
        }else{
          sums[index] = this.sumListfn(column.property,3)
        }
      });

      return sums;
    },
    sumListfn(key,num){
      let sumList = this.tableData1
      let sum = 0
      sum = sumList.reduce((acc, cur) => acc + (cur[key] || 0), 0);
      if(key.indexOf('perShipProfit') != -1){
        return ((sum/sumList.length).toFixed(num))*1
      }
      return (sum.toFixed(num))*1
    },
    sumRatefn(actualkey,targetkey,num){
      let sumList = this.tableData1
      let sumActual = 0
      let sumTarget = 0
      sumActual = sumList.reduce((acc, cur) => acc + (cur[actualkey] || 0), 0);
      sumTarget = sumList.reduce((acc, cur) => acc + (cur[targetkey] || 0), 0);
      if(sumTarget == 0){
        return 0
      }
      return ((sumActual/sumTarget*100).toFixed(num))*1
    },
    sumDifffn(actualkey,targetkey,num){
      let sumList = this.tableData1
      let sumActual = 0
      let sumTarget = 0
      sumActual = sumList.reduce((acc, cur) => acc + (cur[actualkey] || 0), 0);
      sumTarget = sumList.reduce((acc, cur) => acc + (cur[targetkey] || 0), 0);
      return ((sumActual-sumTarget).toFixed(num)) * 1
    },

    getClassList(){
      goodsCategoryList().then((res)=>{
        this.classList = res
      })
    },
    //获取本月时间
    getMonth(type){
      let now = new Date();
      // 获取当前月份和年份
      const month = now.getMonth();
      const year = now.getFullYear();
      // 计算本月第一天的日期
      const startOfMonth = new Date(year, month, 1);
      // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
      const startOfNextMonth = new Date(year, month + 1, 1);
      const endOfMonth = new Date(startOfNextMonth);
      endOfMonth.setDate(startOfNextMonth.getDate() - 1);
      if(type){
        return formatDate(new Date(startOfMonth), 'yyyy-MM')
      }
      return [formatDate(new Date(startOfMonth), 'yyyy-MM-dd'),formatDate(new Date(endOfMonth), 'yyyy-MM-dd')]
    },
    getUserList(){
      getOrderUsersList({departmentId:3,status:1}).then((res)=>{
        this.userList = res;
      })
    },


    //获取列表
    getList1(){
      this.listLoading1 = true;
      this.listQuery1.brandName = this.listQuery1.goodsClass ? this.listQuery1.brandName : ''
      let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
      listQuery.userIds=listQuery.userIds.join(",")
      puserSaleNumAnalysis(listQuery).then(response => {
        this.tableData1 = response
        this.listLoading1 = false;
      }).catch(()=>{
        this.listLoading1 = false;
      });
    },

    handleSizeChange1(val){
      this.listQuery1.pageNum = 1;
      this.listQuery1.pageSize = val;
      this.getList1();
    },
    handleCurrentChange1(val){
      this.listQuery1.pageNum = val;
      this.getList1();
    },

    handleSearchList1(){
      this.listQuery1.pageNum = 1;
      this.getList1();
    },


  },
}
</script>

<style>
.el-table .sum-row{
  background: #f5f7fa
}
.el-table .warning-row {
  background: #fdf5e6;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
